package com.htthorizon.auth.service;

import cn.hutool.core.date.DateUtil;
import com.htthorizon.system.api.exception.UserUnExistException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.htthorizon.common.core.constant.CacheConstants;
import com.htthorizon.common.core.constant.Constants;
import com.htthorizon.common.core.constant.SecurityConstants;
import com.htthorizon.common.core.constant.UserConstants;
import com.htthorizon.common.core.domain.R;
import com.htthorizon.common.core.enums.UserStatus;
import com.htthorizon.common.core.exception.ServiceException;
import com.htthorizon.common.core.text.Convert;
import com.htthorizon.common.core.utils.StringUtils;
import com.htthorizon.common.core.utils.ip.IpUtils;
import com.htthorizon.common.redis.service.RedisService;
import com.htthorizon.common.security.utils.SecurityUtils;
import com.htthorizon.system.api.RemoteUserService;
import com.htthorizon.system.api.domain.SysUser;
import com.htthorizon.system.api.model.LoginUser;

import java.util.Objects;
import java.util.Optional;

/**
 * 登录校验方法
 * 
 * @author mark
 */
@Component
@Slf4j
public class SysLoginService
{
    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysRecordLogService recordLogService;

    @Autowired
    private RedisService redisService;

    /**
     * 登录
     */
    public LoginUser login(String username, String password ,Boolean sso) throws UserUnExistException
    {
        long start = System.currentTimeMillis();
        // 用户名或密码为空 错误
//        if (StringUtils.isAnyBlank(username, password))
//        {
//            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
//            throw new ServiceException("用户/密码必须填写");
//        }
        // 密码如果不在指定范围内 错误
//        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
//                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
//        {
//            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
//            throw new ServiceException("用户密码不在指定范围");
//        }

        R<LoginUser> userInfo1 = remoteUserService.getUserInfo(username, SecurityConstants.INNER);
//        System.out.println(userInfo1);

        SysUser sysUser = Optional.ofNullable(userInfo1).map(R::getData).map(LoginUser::getSysUser).orElse(new SysUser());
        try{
            if (sysUser.getStatus().equals("1")){
                recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "被禁用用户试图登录");
            }
        }catch (NullPointerException e){
            log.error("被禁用用户试图登录: ",e);
            throw new UserUnExistException();
        }

        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new ServiceException("用户名不在指定范围");
        }
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "很遗憾，访问IP已被列入系统黑名单");
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);
        log.info("登录用户远程调用:{}",userResult);

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new UserUnExistException();
        }

        if (R.FAIL == userResult.getCode())
        {
            throw new ServiceException(userResult.getMsg());
        }
        
        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }
//        if(!sso){
//            passwordService.validate(user, password);
//        }
        long end = System.currentTimeMillis();
        log.info("【用户登录】记录数据成功");
        log.info("响应时间:【"+(end-start)+"ms】");
        log.info("请求IP:【"+IpUtils.getIpAddr()+"】");
        log.info("访问服务:【zh-cyhsj-rzgl-rzgl】");
        log.info("请求时间:【"+ DateUtil.date()+"】");
        log.info("请求参数:【{userName:"+username+",password:********】");
        log.info("请求响应码:【"+200+"】");
        log.info("返回参数:【{code:200,msg:'请求成功'}】");


        if (true) {
            // 如果用户不允许多终端同时登录，清除缓存信息
            String userIdKey = CacheConstants.LOGIN_USER_ID_KEY + user.getUserId();
            String userKey = redisService.getCacheObject(userIdKey);
            if (StringUtils.isNotEmpty(userKey))
            {
                redisService.deleteObject(userIdKey);
                redisService.deleteObject(userKey);
                return userInfo;
            }
        }


//        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        return userInfo;
    }

    public void logout(String loginName)
    {
        long start = System.currentTimeMillis();
        recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "退出成功");
        long end = System.currentTimeMillis();
        log.info("【用户退出】记录数据成功");
        log.info("响应时间:【"+(end-start)+"ms】");
        log.info("请求IP:【"+IpUtils.getIpAddr()+"】");
        log.info("访问服务:【zh-cyhsj-rzgl-rzgl】");
        log.info("请求时间:【"+ DateUtil.date()+"】");
        log.info("请求参数:【{userName:"+loginName+"}】");
        log.info("请求响应码:【"+200+"】");
        log.info("返回参数:【{code:200,msg:'请求成功'}】");
    }

    /**
     * 注册
     */
    public void register(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {
            throw new ServiceException("用户/密码必须填写");
        }
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            throw new ServiceException("账户长度必须在2到20个字符之间");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }

        // 注册用户信息
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setNickName(username);
//        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        R<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);

        if (R.FAIL == registerResult.getCode())
        {
            throw new ServiceException(registerResult.getMsg());
        }
        recordLogService.recordLogininfor(username, Constants.REGISTER, "注册成功");
    }

    public static void main(String[] args) {
        String s = SecurityUtils.encryptPassword("Hndl-.2023");
        System.out.println(s);
    }
}
